import { convertImageToBase64 } from "./image";

export async function downloadFile(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath);
        } else {
          reject(new Error("Download failed"));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

export async function saveFile(tempFilePath: string): Promise<string> {
  // 条件编译，只在支持 uni.saveFile 的平台上调用
  // #ifdef MP-WEIXIN || APP-PLUS
  return new Promise((resolve, reject) => {
    uni.saveFile({
      tempFilePath: tempFilePath,
      success: (res) => {
        resolve(res.savedFilePath);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
  // #endif

  // #ifndef MP-WEIXIN || APP-PLUS
  return Promise.resolve(tempFilePath);
  // #endif
}

export async function downloadFileAsBase64(url: string): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    // 条件编译，只在支持 uni.getFileSystemManager 的平台上调用
    // #ifndef H5
    uni.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          const filePath = res.tempFilePath;
          const fs = uni.getFileSystemManager();
          fs.readFile({
            filePath: filePath,
            encoding: "base64",
            success: (res) => {
              resolve(res.data as string); // 确保返回类型为 string
            },
            fail: (err) => {
              console.error(
                "downloadFileAsBase64 - app - Failed to read file:",
                err
              );
              reject(err);
            },
          });
        } else {
          reject(new Error("Download failed"));
        }
      },
      fail: (err) => {
        console.error("downloadFileAsBase64 - h5 - Failed to read file:", err);
        reject(err);
      },
    });
    // #endif
    // #ifdef H5
    resolve(url);
    // #endif
  });
}
